﻿using System;
using MayhemWP7.Modules.Events.GeoLocation;
using Microsoft.Phone.Controls;
using System.Device.Location;
using MayhemCore;

namespace MayhemWP7.Modules.Pages
{
    public partial class LeaveRadiusConfig : PhoneApplicationPage
    {
        private LeaveRadius module;
        private GeoCoordinateWatcher watcher;

        public LeaveRadiusConfig()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // Get the index of the connection in the connection list
            int connectionIndex = Int32.Parse(NavigationContext.QueryString["id"]);

            module = (LeaveRadius)Mayhem.Instance.ConnectionList[connectionIndex].Event;
            this.DataContext = module;

        }

        private void CenterButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            GetCoordinate();
        }

        private void GetCoordinate()
        {
            // The watcher variable was previously declared as type GeoCoordinateWatcher. 
            if (watcher == null) {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High); // Use high accuracy.
                watcher.MovementThreshold = 1; // Use MovementThreshold to ignore noise in the signal.
                watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            }
            watcher.TryStart(false, TimeSpan.FromSeconds(45));
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Ready) {
                // Use the Position property of the GeoCoordinateWatcher object to get the current location.

                module.Center = watcher.Position.Location;
                //Stop the Location Service to conserve battery power.
                watcher.Stop();
            }
        }
    }
}